/**
 * Created by wangjz on 2019/02/26.
 */
import React, { Component, PropTypes } from 'react';
import { Select, Form, Row, Col } from 'antd';
import { listOrg } from './Service';


class OrgSelect extends Component {
  selectRef = React.createRef();
  state = { orgList: [], loading: false };

  constructor(props) {
    super(props);

  }

  componentDidMount() {
    this.onload();
  }

  onload = async () => {
    const result = await listOrg();
    this.setState({ orgList: result.dataSource, visible: result.visible });
    if (this.props.onload) {
      this.props.onload({ row: result.dataSource[0], visible: result.visible });
    }
  };

  onSearch = async value => {
    this.setState({ value: value });
    this.setState({ loading: true });
    const result = await listOrg(value);
    this.setState({ orgList: result.dataSource, loading: false });
  };

  onSelect = value => {
    this.setState({ value: value });
    if (this.props.onSelect) {
      this.props.onSelect(value);
    }
  };

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.state.value == null && this.state.orgList.length > 0) {
      this.setState({ value: this.state.orgList[0].id });
    }
  }

  render() {
    return (
      <Select placeholder='所属机构' style={{width: '100%', display: this.state.visible ? '': 'none', ...this.props.style}}
              showArrow={false} showSearch={true} value={this.state.value}
              filterOption={false} loading={this.state.loading}
              onSearch={value => this.onSearch(value)}
              onSelect={this.onSelect}>
        {this.state.orgList.map(function(item, i) {
          if (!item.id) return;
          return <Select.Option key={item.id}
                                value={item.id}>{item.name}</Select.Option>;
        })}
      </Select>
    );
  }
}

export default OrgSelect;
